package com.wsoft.excel.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wsoft.constant.ExcelConstant;
import lombok.Getter;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author z001
 * @Date 2024/11/12 11:03
 */
public class FormAnalysisEventListener extends AnalysisEventListener<Map<Integer, String>> {

    /**
     * key: excel 第几行数据
     * map: key 表头中文,value: excel数据
     */
    @Getter
    private  List<Map<Integer, Map<String, Object>>> resultList = new ArrayList<>();
    private  List<String> headerList = new ArrayList<>();
    /**
     * 当前sheet索引页
     */
    private int currentSheetIndex = -1;
    private  Map<Integer, Map<String, Object>> currentSheetData = new HashMap<>();
    @Getter
    private String parentId;

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        // 获取第一行和第二行的表头信息
        headMap.forEach((key, value) -> {
            String parentId = getParentId(value);
            if (key == 0 && StrUtil.isNotBlank(parentId)) {
                this.parentId = parentId;
            }
        });
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        int rowIndex = context.readRowHolder().getRowIndex();
        int sheetIndex = context.readSheetHolder().getSheetNo();

        // 如果Sheet页发生变化，重置表头信息并存储当前Sheet页的数据
        if (sheetIndex != currentSheetIndex) {
            currentSheetData = new HashMap<>(16);
            headerList = new ArrayList<>();
            currentSheetIndex = sheetIndex;
        }

        if (rowIndex == 1) {
            // 获取第二行的表头信息
            data.forEach((key, value) -> headerList.add(value));
            return;
        }
        if (rowIndex < ExcelConstant.EXCEL_HEADER_LINE) {
            // 跳过前两行（第一行和第二行表头）
            return;
        }

        Map<String, Object> rowData = new LinkedHashMap<>();
        data.forEach((key, value) -> {
            rowData.put(headerList.get(key), value);
        });
        currentSheetData.put(rowIndex, rowData);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 所有数据解析完成后的操作
        if (!currentSheetData.isEmpty()) {
            resultList.add(currentSheetData);
        }
    }

    /**
     * 从模板中 获取父表ID
     *
     * @param value
     * @return
     */
    private String getParentId(String value) {
        if (StrUtil.isBlank(value)) {
            return null;
        }
        // 使用正则表达式提取数字
        Pattern pattern = Pattern.compile(ExcelConstant.TEMPLATE1.replace(StrUtil.EMPTY_JSON, "(\\d+)"));
        Matcher matcher = pattern.matcher(value);

        if (matcher.find()) {
            return matcher.group(1);
        } else {
            return null;
        }
    }
}
